package com.elm_springboot_s.service.impl;

import com.elm_springboot_s.mapper.OrdersMapper;
import com.elm_springboot_s.pojo.Orders;
import com.elm_springboot_s.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    @Transactional
    public int createOrders(Long userId, Integer businessId, Integer daId, Double orderTotal) {
        // 1.创建订单对象
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setBusinessId(businessId);
        orders.setDaId(daId);
        orders.setOrderTotal(orderTotal);
        
        // 2.保存订单并获取生成的订单ID
        ordersMapper.saveOrders(orders); // 这里会自动设置orders的orderId
        int orderId = orders.getOrderId();
        
        // 3.将购物车数据批量添加到订单明细表
        if (orderId > 0) {
            ordersMapper.saveOrderDetailetFromCart(orderId, userId, businessId);
            // 4.清空购物车
            ordersMapper.removeCart(userId, businessId);
        }
        
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(Long userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
} 